import { markdownFileToDocx, MarkdownToDocx, markdownToDocx } from './markdown-to-docx.js';
import { markdownFileToPdf, MarkdownToPdf, markdownToPdf } from './markdown-to-pdf.js';
import type {
  BatchConversionOptions,
  BatchConversionResult,
  ConversionError,
  ConversionOptions,
  ConversionResult,
  ConverterOptions,
  DocxOptions,
  PdfOptions,
} from './types.js';

/**
 * 支持Markdown转PDF/DOCX，包含中文字体和Mermaid图表支持
 */
export class DocumentConverter {
  private options: Required<ConverterOptions>;

  constructor(options: ConverterOptions = {}) {
    this.options = {
      // 默认输出目录
      outputDir: './output',
      // 中文字体配置
      chineseFont: 'PingFang SC, Microsoft YaHei, SimSun, sans-serif',
      // Mermaid主题
      mermaidTheme: 'default',
      // PDF特定选项
      pdf: {
        format: 'A4',
        margin: { top: '1in', right: '0.8in', bottom: '1in', left: '0.8in' },
        printBackground: true,
        displayHeaderFooter: false,
        preferCSSPageSize: true,
        landscape: false,
        ...options.pdf,
      },
      // DOCX特定选项
      docx: {
        title: 'Document',
        creator: 'Markdown Converter',
        description: 'Generated from Markdown',
        chineseFont: 'Microsoft YaHei',
        englishFont: 'Calibri',
        codeFont: 'Consolas',
        fontSize: 22,
        headingColor: '2F5597',
        linkColor: '0563C1',
        mermaidWidth: 600,
        mermaidHeight: 400,
        ...options.docx,
      },
      ...options,
    };
  }

  /**
   * 转换Markdown内容为PDF
   */
  async toPdf(
    markdownContent: string,
    outputPath: string,
    options: ConversionOptions = {}
  ): Promise<ConversionResult> {
    const converter = new MarkdownToPdf({
      ...this.options.pdf,
      chineseFont: this.options.chineseFont,
      mermaidTheme: this.options.mermaidTheme,
      ...options,
    });

    return await converter.convertToPdf(markdownContent, outputPath, options);
  }

  /**
   * 转换Markdown文件为PDF
   */
  async fileToPdf(
    markdownFilePath: string,
    outputPath: string,
    options: ConversionOptions = {}
  ): Promise<ConversionResult> {
    const converter = new MarkdownToPdf({
      ...this.options.pdf,
      chineseFont: this.options.chineseFont,
      mermaidTheme: this.options.mermaidTheme,
      ...options,
    });

    return await converter.convertFromFile(markdownFilePath, outputPath, options);
  }

  /**
   * 转换Markdown内容为DOCX
   */
  async toDocx(
    markdownContent: string,
    outputPath: string,
    options: ConversionOptions = {}
  ): Promise<ConversionResult> {
    const converter = new MarkdownToDocx({
      ...this.options.docx,
      ...options,
    });

    return await converter.convertToDocx(markdownContent, outputPath, options);
  }

  /**
   * 转换Markdown文件为DOCX
   */
  async fileToDocx(
    markdownFilePath: string,
    outputPath: string,
    options: ConversionOptions = {}
  ): Promise<ConversionResult> {
    const converter = new MarkdownToDocx({
      ...this.options.docx,
      ...options,
    });

    return await converter.convertFromFile(markdownFilePath, outputPath, options);
  }

  /**
   * 批量转换：同时生成PDF和DOCX
   */
  async toBoth(
    markdownContent: string,
    baseOutputPath: string,
    options: BatchConversionOptions = {}
  ): Promise<BatchConversionResult> {
    const pdfPath = `${baseOutputPath}.pdf`;
    const docxPath = `${baseOutputPath}.docx`;

    const results = await Promise.allSettled([
      this.toPdf(markdownContent, pdfPath, options.pdf),
      this.toDocx(markdownContent, docxPath, options.docx),
    ]);

    return {
      pdf:
        results[0]?.status === 'fulfilled'
          ? results[0].value
          : { success: false, error: results[0]?.reason || new Error('PDF转换失败') },
      docx:
        results[1]?.status === 'fulfilled'
          ? results[1].value
          : { success: false, error: results[1]?.reason || new Error('DOCX转换失败') },
      success: results.some(result => result.status === 'fulfilled'),
    };
  }

  /**
   * 批量转换文件：同时生成PDF和DOCX
   */
  async fileToBoth(
    markdownFilePath: string,
    baseOutputPath: string,
    options: BatchConversionOptions = {}
  ): Promise<BatchConversionResult> {
    const pdfPath = `${baseOutputPath}.pdf`;
    const docxPath = `${baseOutputPath}.docx`;

    const results = await Promise.allSettled([
      this.fileToPdf(markdownFilePath, pdfPath, options.pdf),
      this.fileToDocx(markdownFilePath, docxPath, options.docx),
    ]);

    return {
      pdf:
        results[0]?.status === 'fulfilled'
          ? results[0].value
          : { success: false, error: results[0]?.reason || new Error('PDF转换失败') },
      docx:
        results[1]?.status === 'fulfilled'
          ? results[1].value
          : { success: false, error: results[1]?.reason || new Error('DOCX转换失败') },
      success: results.some(result => result.status === 'fulfilled'),
    };
  }
}

// 导出工具类
export { MarkdownToDocx, MarkdownToPdf };

// 导出类型
export type {
  BatchConversionOptions,
  BatchConversionResult,
  ConversionError,
  ConversionOptions,
  ConversionResult,
  ConverterOptions,
  DocxOptions,
  PdfOptions,
};

// 导出便捷函数
export { markdownFileToDocx, markdownFileToPdf, markdownToDocx, markdownToPdf };

/**
 * 创建默认转换器实例
 */
export function createConverter(options: ConverterOptions = {}): DocumentConverter {
  return new DocumentConverter(options);
}

/**
 * 快速转换函数：Markdown内容转PDF
 */
export async function quickToPdf(
  markdown: string,
  outputPath: string,
  options: PdfOptions & ConversionOptions = {}
): Promise<ConversionResult> {
  const converter = createConverter({ pdf: options });
  return await converter.toPdf(markdown, outputPath, options);
}

/**
 * 快速转换函数：Markdown内容转DOCX
 */
export async function quickToDocx(
  markdown: string,
  outputPath: string,
  options: DocxOptions & ConversionOptions = {}
): Promise<ConversionResult> {
  const converter = createConverter({ docx: options });
  return await converter.toDocx(markdown, outputPath, options);
}

/**
 * 快速转换函数：同时生成PDF和DOCX
 */
export async function quickToBoth(
  markdown: string,
  basePath: string,
  options: BatchConversionOptions = {}
): Promise<BatchConversionResult> {
  const converter = createConverter();
  return await converter.toBoth(markdown, basePath, options);
}

/**
 * 默认导出：创建转换器实例
 */
export default createConverter;

// ==== MCP 工具包导出 ====
// 为了支持工具注册器自动发现，从mcp-tools导出工具包
export { default as mcpPackage, meta, tools } from './mcp-tools.js';
